# 作者：宋安康
# 开发时间：2023/6/11 20:06
from PyQt5 import QtWidgets, QtGui
import socket


class ChatClient(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("Chat Client")

        self.text_edit = QtWidgets.QTextEdit(self)
        self.text_edit.setReadOnly(True)
        self.text_edit.setGeometry(10, 10, 280, 280)

        self.line_edit = QtWidgets.QLineEdit(self)
        self.line_edit.setGeometry(10, 300, 200, 20)

        self.send_button = QtWidgets.QPushButton("Send", self)
        self.send_button.setGeometry(220, 300, 70, 20)

        self.send_button.clicked.connect(self.send_message)

        self.show()

        self.HOST = '127.0.0.1'
        self.PORT = 8000

        self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client_socket.connect((self.HOST, self.PORT))

    def send_message(self):
        msg = self.line_edit.text()
        self.client_socket.send(msg.encode())
        if msg == "quit":
            self.line_edit.setReadOnly(True)
        reply = self.client_socket.recv(1024).decode()
        self.text_edit.append("You: " + msg)
        self.text_edit.append("Server: " + reply)
        self.line_edit.clear()

if __name__ == "__main__":
    app = QtWidgets.QApplication([])

    client = ChatClient()

    app.exec_()
